package com.catcoin.hhtb.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.catcoin.hhtb.aliyun.OSSResultModel;
import com.catcoin.hhtb.mapper.UsersRechargeMapper;
import com.catcoin.hhtb.model.UsersRecharge;
import com.catcoin.hhtb.service.DepfeignInterface;
import com.catcoin.hhtb.service.IUsersRechargeService;
import com.catcoin.hhtb.util.FileUtils;
import com.catcoin.hhtb.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户充值表 服务实现类
 * </p>
 *
 * @author 
 * @since 2018-09-15
 */
@Service
public class UsersRechargeServiceImpl extends ServiceImpl<UsersRechargeMapper, UsersRecharge> implements IUsersRechargeService {
    @Autowired
    private DepfeignInterface depositfeignInterface;
    @Autowired
    private FileUtils fileUtils;
    @Override
    public String aliyunUpload(HttpServletRequest request){
        //上传汇款单
        String aliyunUpload = depositfeignInterface.aliyunUpload(request);
        String url="";
        JSONObject jsonObject = JSONObject.parseObject(aliyunUpload);
        if("1".equals(jsonObject.get("status").toString())){
            JSONObject jsonObject1 = JSONObject.parseObject(jsonObject.get("data").toString());
            url=  jsonObject1.get("url").toString();
        }

        return url;
    }

    @Override
    @Transactional
    public Map<String,Object> addUsersRecharge(HttpServletRequest request){
        Map<String,Object> resultMap=new HashMap<>();
        try{
            UsersRecharge usersRecharge=new UsersRecharge();
            String userIds = request.getParameter("userId");
            if (userIds==null || "".equals(userIds)){
                resultMap.put("code","00");
                resultMap.put("msg","您还未登录，请重新登录");
                return resultMap;
            }
            Integer userId=Integer.parseInt(userIds);
            String orderNo = StringUtils.getOrderIdByTime("H");
            Integer  payType=1;
            String cashs=request.getParameter("cash");
            if (cashs==null || "".equals(cashs)){
                resultMap.put("code","00");
                resultMap.put("msg","输入金额不能为空");
                return resultMap;
            }
            Integer cash=Integer.parseInt(cashs);
            if (cash.equals(0)){
                resultMap.put("code","00");
                resultMap.put("msg","输入金额不能为0");
                return resultMap;
            }
            String  remark="现金充值";
            Date date=new Date();
            usersRecharge.setUserId(userId);
            usersRecharge.setOrderNo(orderNo);
            usersRecharge.setPayType(payType);
            usersRecharge.setCash(new BigDecimal(cash));
            usersRecharge.setRemark(remark);
            usersRecharge.setCreateTime(date);
            this.insert(usersRecharge);
            resultMap.put("orderNo",usersRecharge.getOrderNo());
            resultMap.put("code","01");
            resultMap.put("msg","生成订单成功");
            return resultMap;

        }catch (Exception e){
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            resultMap.put("code","00");
            resultMap.put("msg","生成订单失败");
            return resultMap;
        }
    }
    @Override
    @Transactional
     public Map<String,Object> addImg(HttpServletRequest request){
         Map<String,Object> resultMap=new HashMap<>();
         try{
             String orderNo = request.getParameter("orderNo");
             UsersRecharge usersRecharge=new UsersRecharge();
             usersRecharge.setOrderNo(orderNo);
             EntityWrapper<UsersRecharge> entityWrapper =new EntityWrapper<UsersRecharge>(usersRecharge);
             UsersRecharge usersRecharge1 = this.selectOne(entityWrapper);
             //上传汇款单
             String url ="";
             Map<String, Object> map=this.upload(request);
             if ("00".equals(map.get("code").toString())){
                 resultMap.put("code","00");
                 resultMap.put("msg","上传汇款单失败");
                 return resultMap;
             }
             if("01".equals(map.get("code").toString())){
                 url=  map.get("url").toString();
             }
             usersRecharge1.setOrderImg(url);
             this.updateById(usersRecharge1);
             resultMap.put("code","01");
             resultMap.put("msg","上传汇款单成功");
             return resultMap;
         }catch (Exception e){
             e.printStackTrace();
             TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
             resultMap.put("code","00");
             resultMap.put("msg","上传汇款单失败");
             return resultMap;
         }
     }


    /**
     * 图片上传阿里云
     * @return
     * @throws IOException
     */
//    @Override
    public Map<String,Object> upload(HttpServletRequest req){
        Map<String,Object> map = new HashMap<String, Object>();

        MultipartHttpServletRequest mReq  =  null;
        List<MultipartFile> files = null;
        InputStream is = null ;
        OSSResultModel ossResult = null;
        String fileName = "";
        // 原始文件名   UEDITOR创建页面元素时的alt和title属性
        String originalFileName = "";

        try {
            mReq = (MultipartHttpServletRequest)req;
            // 从config.json中取得上传文件的ID
            files = mReq.getFiles("file");
            String  url="";
            for (MultipartFile file:files){
                // 取得文件的原
                fileName = file.getOriginalFilename();
                originalFileName = fileName;
                if(!com.alibaba.druid.util.StringUtils.isEmpty(fileName)){
                    is = file.getInputStream();
                    fileName = fileUtils.reName(fileName);
                    ossResult = fileUtils.saveFile(fileName, is);
                } else {
                    throw new IOException("文件名为空!");
                }

                String[] strings = new String[5];
                strings[0] = ossResult.getUrl();
                url=strings[0]+","+url;
            }


            map.put("code","01");
            map.put("url",url);
        }
        catch (Exception e) {
            map.put("code","00");
            map.put("msg","图片上传失败");
            System.out.println("文件 "+fileName+" 上传失败!");
        }

        return map;
    }
}
